package com.study.talk.app.register.fragment;


import static androidx.navigation.fragment.FragmentKt.findNavController;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.study.talk.app.base.EventBusBaseFragment;
import com.study.talk.R;
import com.study.talk.databinding.FragmentPhoneNumberBinding;
import com.study.talk.netty.NettyClient;
import com.study.talk.netty.message.request.SmsSendRequest;
import com.study.talk.netty.message.response.SmsSendResponse;
import com.study.talk.util.ToastUtil;
import com.study.talk.util.VerificationUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public class PhoneNumberFragment extends EventBusBaseFragment {

    private FragmentPhoneNumberBinding fragmentPhoneNumberBinding;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        fragmentPhoneNumberBinding = FragmentPhoneNumberBinding.inflate(inflater,container,false);
        return fragmentPhoneNumberBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        fragmentPhoneNumberBinding.toCodeBtn.setOnClickListener(v -> {
            checkInput(fragmentPhoneNumberBinding.registerUsername,"请输入用户名");
            checkInput(fragmentPhoneNumberBinding.registerPhoneNumber,"请输入手机号码");

            if (!VerificationUtil.isValidTelNumber(editTrim(fragmentPhoneNumberBinding.registerPhoneNumber))){
                ToastUtil.showToast(getContext(),"请输入正确的手机号码");
                return;
            }
            String username = fragmentPhoneNumberBinding.registerUsername.getText().toString();

            if (username.length() < 6) {
                ToastUtil.showToast(getContext(),"用户名长度不能小于6");
                return;
            }

            String phoneNumber = fragmentPhoneNumberBinding.registerPhoneNumber.getText().toString();
            NettyClient.sendMessage(new SmsSendRequest(username,phoneNumber));
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSmsMessage(SmsSendResponse message){
        if (message.getStatus().equals("OK")){
            Bundle bundle = new Bundle();
            bundle.putString("code",message.getCode());
            bundle.putString("phoneNumber",message.getPhoneNumber());
            bundle.putString("username",message.getUsername());
            findNavController(this).navigate(R.id.action_phoneNumberFragment_to_codeFragment,bundle);
        }else {
            ToastUtil.showToast(getContext(),message.getMessage());
        }

    }
}